package main

import (
	"bee-study/grpc/api"
	"context"
	"google.golang.org/grpc"
	"log"
	"net"
)

const (
	port = ":50051"
)

// server is used to implement helloworld.GreeterServer.
// 继承 UnimplementedGreeterServer 服务
type server struct {
	api.UnimplementedGreeterServer
}


// 重写 UnimplementedGreeterServer 的 SayHello 方法 implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *api.HelloRequest) (*api.HelloReply, error) {
	log.Printf("Received: %v", in.GetName())
	return &api.HelloReply{Message: "Hello " + in.GetName()}, nil
}

func interceptorTest1(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
	log.Printf("测试一下")
	return nil
}

func interceptorTest2(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
	resp, err = handler(ctx, req) // 响应后
	log.Printf("interceptorTest2 测试一下")
	// resp, err = handler(ctx, req)  // 响应前
	return
}

func main() {
	lis, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer(grpc.MaxConcurrentStreams(2), grpc.ChainStreamInterceptor(interceptorTest1), grpc.UnaryInterceptor(interceptorTest2))
	api.RegisterGreeterServer(s, &server{})
	log.Printf("server listening at %v", lis.Addr())
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
